<style lang="less">
.banner {
  width: 100%;

  .banner-header {
    padding-top: 15px;
    margin-bottom: 20px;
  }

  .banner-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0px;
  }

  .banner-list-title {
    margin: 0;
    color: #303133;
  }

  .search-box {
    margin: 0;
  }

  .banner-form,
  .banner-table {
    padding-top: 15px;

    .opt {
      margin-bottom: 15px;
    }

    .preview-img {
      width: 360px;
      height: 180px;
      border-radius: 4px;
    }

    .el-upload-list {
      display: none;
    }
  }
}
</style>
<template>
  <div class="banner">
    <div class="banner-header">
      <el-button :type="num == 1 ? 'primary' : ''" @click="num = 1">发布广告</el-button>
      <el-button :type="num == 2 ? 'primary' : ''" @click="num = 2">广告列表</el-button>
    </div>

    <div v-if="num == 1" class="banner-form">
      <el-form :model="banner" label-width="100px">
        <el-form-item label="广告标题">
          <el-input v-model="banner.title" placeholder="请输入广告标题"></el-input>
        </el-form-item>
        <el-form-item label="广告链接">
          <el-input v-model="banner.link" placeholder="请输入广告链接"></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <div style="display: flex;">
            <el-upload class="upload-demo" drag action="" :on-change="changeFn" :auto-upload="false" accept="image/*">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <div v-if="src" style="text-align: center; margin-left: 15px">
              <img class="preview-img" :src="src" alt="预览图">
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitBannerFn">点击发布</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-if="num == 2" class="banner-table">
      <div class="banner-list-header">
        <h3 class="banner-list-title">广告列表</h3>
        <div class="search-box">
          <el-input v-model="search" size="small" placeholder="输入关键字搜索（标题或链接）" clearable @clear="handleSearchClear"
            @keyup.enter.native="handleSearch" style="width: 300px;">
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </div>
      </div>
      <div class="banner-list-wrap">
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column label="序号" width="80" align="center">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="ID" prop="id" width="80" align="center"></el-table-column>
          <el-table-column label="标题" prop="banner_title"></el-table-column>
          <el-table-column label="链接">
            <template slot-scope="scope">
              <a :href="scope.row.banner_link" target="_blank" style="color: #a0d8ef;">{{ scope.row.banner_link }}</a>
            </template>
          </el-table-column>
          <el-table-column label="图片" width="180">
            <template slot-scope="scope">
              <el-image style="width: 150px; height: 100px" :src="scope.row.src" :preview-src-list="[scope.row.src]"
                fit="cover">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column align="right" width="200">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog title="修改广告" :visible.sync="centerDialogVisible" width="40%" center>
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="广告标题">
          <el-input v-model="editForm.title" placeholder="请输入广告标题"></el-input>
        </el-form-item>
        <el-form-item label="广告链接">
          <el-input v-model="editForm.link" placeholder="请输入广告链接"></el-input>
        </el-form-item>
        <el-form-item label="当前图片">
          <img v-if="editForm.imgUrl" :src="editForm.imgUrl"
            style="width: 100%; max-height: 300px; border-radius: 4px;">
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyBannerFn">保存修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadPhoto, publishBanner, listBanner, removeBanner, removePhoto, searchBanner, modifyBanner, host } from '../api/index'
import { requireLogin } from '../utils/auth'

export default {
  data() {
    return {
      centerDialogVisible: false,
      banner: {
        title: "",
        link: ""
      },
      src: "",
      tableData: [],
      search: '',
      num: 2,
      file: null,
      editForm: {
        title: "",
        link: "",
        imgUrl: "",
        picUrl: "",
        id: ""
      }
    }
  },
  methods: {
    // 搜索轮播图
    async searchBannerFn() {
      const keyword = this.search ? this.search.trim() : ''
      if (!keyword) {
        // 如果关键词为空，加载普通列表
        this.listBannerFn()
        return
      }

      await searchBanner({ keyword })
        .then(resData => {
          if (resData.code == 200) {
            let { result } = resData
            // 处理搜索结果，如果result为空或undefined，则使用空数组
            const searchResults = Array.isArray(result) ? result : []
            let newArr = searchResults.map(item => {
              item.src = host + item.banner_url
              return item
            })
            this.tableData = newArr
            // 如果搜索无结果，可以给出提示（可选）
            if (searchResults.length === 0) {
              // 不显示错误，只是清空列表，让用户知道没有搜索结果
            }
          } else {
            this.tableData = []
            this.$showError && this.$showError('搜索失败', resData.msg || '搜索广告时发生错误')
          }
        })
        .catch(err => {
          console.error('搜索广告失败:', err)
          this.tableData = []
          this.$showError && this.$showError('搜索失败', '搜索广告时发生错误，请重试')
        })
    },
    // 搜索处理
    handleSearch() {
      const keyword = this.search ? this.search.trim() : ''
      if (keyword) {
        this.searchBannerFn()
      } else {
        this.listBannerFn()
      }
    },
    // 清空搜索
    handleSearchClear() {
      this.search = ''
      this.listBannerFn()
    },
    // 删除轮播图
    async removeBannerFn(row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      const result = await this.$showConfirm('提示', '您确定要删除该记录吗?', '确定', '取消')
      if (result.isConfirmed) {
        await removeBanner({ id: row.id })
          .then(resData => {
            if (resData.code == 200) {
              this.$showSuccess('成功', '删除成功')
              // 如果有搜索关键词，重新执行搜索，否则加载列表
              if (this.search && this.search.trim()) {
                this.searchBannerFn()
              } else {
                this.listBannerFn()
              }
              if (row.banner_url) {
                removePhoto({ picUrl: row.banner_url }).then(() => { })
              }
            } else {
              this.$showError('失败', resData.msg || '删除失败')
            }
          })
          .catch(() => {
            this.$showError('失败', '删除失败，请重试')
          })
      }
    },
    // 获取轮播图列表
    async listBannerFn() {
      await listBanner().then(resData => {
        if (resData.code == 200) {
          let { result } = resData
          let newArr = result.map(item => {
            item.src = host + item.banner_url
            return item
          })
          this.tableData = newArr
        }
      })
    },
    // 发布轮播图
    async submitBannerFn() {
      // 检查登录状态
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      if (this.banner.title == '' || this.banner.link == '') {
        this.$showError('提示', '输入框不能为空')
        return false
      }
      if (this.src == '') {
        this.$showError('提示', '请上传图片')
        return false
      }
      try {
        let result = await this.uploadPhotoFn()
        if (!result || !result.picUrl) {
          this.$showError('失败', '图片上传失败，请重试')
          return false
        }
        await publishBanner({
          banner_title: this.banner.title,
          banner_link: this.banner.link,
          banner_url: result.picUrl
        })
          .then(resData => {
            if (resData.code == 200) {
              this.listBannerFn()
              this.num = 2
              this.banner.title = ""
              this.banner.link = ""
              this.src = ""
              this.file = null
              this.$showSuccess('成功', '发布成功')
            } else {
              this.$showError('失败', resData.message || resData.msg || '发布失败')
            }
          })
          .catch(error => {
            console.error('发布广告失败:', error)
            this.$showError('失败', '发布失败，请检查网络连接或联系管理员')
          })
      } catch (error) {
        console.error('上传图片失败:', error)
        this.$showError('失败', '图片上传失败，请检查网络连接或后端服务是否正常运行')
      }
    },
    // 上传图片
    async uploadPhotoFn() {
      let formData = new FormData()
      formData.append('photo', this.file)
      return await uploadPhoto(formData)
    },
    // 预览图片
    changeFn(info) {
      let file = info.raw
      const reader = new FileReader()
      reader.onload = () => {
        this.src = reader.result
      }
      if (file) {
        this.file = file
        reader.readAsDataURL(file)
      }
      return false
    },
    // 保存修改
    async modifyBannerFn() {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      let { title: banner_title, link: banner_link, picUrl: banner_url, id } = this.editForm
      await modifyBanner({ banner_title, banner_link, banner_url, id }).then(resData => {
        if (resData.code == 200) {
          // 如果有搜索关键词，重新执行搜索，否则加载列表
          if (this.search && this.search.trim()) {
            this.searchBannerFn()
          } else {
            this.listBannerFn()
          }
          this.centerDialogVisible = false
          this.$showSuccess('成功', '修改成功')
        } else {
          this.$showError('失败', resData.msg || '修改失败')
        }
      })
        .catch(() => {
          this.$showError('失败', '修改失败，请重试')
        })
    },
    // 编辑
    async handleEdit(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }
      this.centerDialogVisible = true
      this.editForm.title = row.banner_title
      this.editForm.link = row.banner_link
      this.editForm.imgUrl = row.src
      this.editForm.picUrl = row.banner_url
      this.editForm.id = row.id
    },
    // 删除
    async handleDelete(index, row) {
      if (row.id) {
        await this.removeBannerFn(row)
      }
    }
  },
  created() {
    this.listBannerFn()
    this.$store.commit("addTab", this.$route)
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(newRoute) {
        this.$store.commit("addTab", newRoute)
      }
    }
  }
}
</script>
